/**
 * @(#)ICodeManage.java 07/23/2013
 *
 * Copyright (c) 2013 S9,Inc.All rights reserved.
 * Created by 2013-07-23 
 */
package cn.jdy.authority.service;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jdy.authority.entity.SysRole;
import cn.jdy.authority.entity.UserRole;
import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.StringUtil;

/**
 * 角色管理业务处理接口实现类 对角色进行增删改查等操作
 *
 * @author: ZhangLi
 * @date: 2013-7-23
 */
@Service
public class SysRoleService extends BaseDao<SysRole> {
  @Autowired
  UserRoleService userRoleService;
  @Autowired
  UserService userService;
  @Autowired
  RoleMenuService roleMenuService;


	/**
	 * 根据
	 * @param role
	 * @return
	 */
	public int count(SysRole role) {
		int count = 0;
		try {
		  SQLQuery query = super.em().createSQLQuery("select count(0) from userrole a," + " user u where u.id = a.userid and a.roleid = ?");
			query.setParameter(0, role.getId());
			count = Integer.parseInt(String.valueOf(query.uniqueResult()));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询会员信息异常", e);
		}
		return count;
	}

	/**
	 * 将选中那个的用户插入角色中
	 *
	 * @param userId 用户标识数组
	 * @param roleId 角色标识
	 * @description: 将用户和角色的关系插入关系表中S9_SYS_USER_ROLE_RELA
	 * @author:zhangli
	 * @date:2013-8-1
	 */
	@Transactional
	public void addUserToRole(String userId, String roleId) {
		try {
			String[] userIds = userId.split(",");
			for(int i = 0; i < userIds.length; i++) {
			  UserRole userrole = new UserRole();
			  userrole.setRoleid(roleId);
			  userrole.setUserid(userIds[i]);
			  userRoleService.save(userrole);
			  
/*			  
			  User user = userService.find(userIds[i]);
			  String newRoleid = "";
			  if ("".equals(user.getRoleid())) {
				  newRoleid = roleId;
			  } else {
				  newRoleid = user.getRoleid() + "," + roleId;
			  }
			  user.setRoleid(newRoleid);
			  userService.update(user);
*/			  
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "addUserToRole将用户放入角色中失败", e);
			throw new BaseException("addUserToRole将用户放入角色中失败");
		}
	}

	/**
	 * 从角色中删除关联的用户
	 *
	 * @param userid 用户标识数组
	 * @param roleid 角色标识
	 * @description: 将S9_SYS_USER_ROLE_RELA与roleId这个角色关联的用户关系数据删掉
	 * @author:zhangli
	 * @date:2013-8-1
	 */
	@Transactional
	public void delUserFromRole(String userid, String roleid) {
		try {
			if(userid != null && userid.length() > 0) {
				Object[] userids = userid.split(",");
				super.em().createSQLQuery("delete from userrole where roleid =:roleid and userid in(:userid)")
				.setParameter("roleid", roleid)
				.setParameterList("userid", userids)
				.executeUpdate();
/*				
				for (Object userId : userids) {
					User user = userService.find(userId.toString());
					String newRoleid = "";
					String [] roles = user.getRoleid().split(",");
					for (String roleId : roles) {
						if (!roleId.equals(roleid)) {
							if ("".equals(newRoleid)) {
								newRoleid = roleId;
							} else {
								newRoleid += "," + roleId;
							}
						}
					}
					user.setRoleid(newRoleid);
					userService.update(user);
				}
*/				
			}
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "delUserFromRole从角色中删除用户失败", e);
		}
	}
	
	/**
	 * 删除角色
	 *
	 * @param：roleid 角色标识
	 * @author：luzhirui
	 * @date：2015-09-22
	 */
	@Transactional
	public void delRole(String id) {
		try {
/*			
			// 查询角色对应用户，更新user表的roleid字段
			List<UserRole> userroleList = userRoleService.find("roleid", id);
			for (UserRole userrole : userroleList) {
				User user = userService.find(userrole.getUserid());
				String newRoleid = "";
				String [] roles = user.getRoleid().split(",");
				for (String roleid : roles) {
					if (!roleid.equals(id)) {
						if ("".equals(newRoleid)) {
							newRoleid = roleid;
						} else {
							newRoleid += "," + roleid;
						}
					}
				}
				user.setRoleid(newRoleid);
				userService.update(user);
			}
*/			
			// 删除角色与菜单对应关系
			roleMenuService.delete("roleid", id);
			
			// 删除角色与用户对应关系
			userRoleService.delete("roleid", id);
			
			// 删除角色
			super.delete(id);
			
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "删除角色失败", e);
			throw new BaseException("删除角色失败");
		}
	}
	
	/**
	 * 获取角色信息
	 * @param rolename
	 * @param isactive
	 * @return
	 */
	public SysRole findOneByRoleName(String rolename, String isactive ){
		SysRole role = null;
		try {
		  role = super.findOne(createFilter(rolename, isactive));
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询会员信息异常", e);
		}
		return role;
	}
	
	/**
	 * 拼装条件(角色名称，状态)
	 * @param rolename
	 * @param isactive
	 * @return
	 */
	private DetachedCriteria createFilter(String rolename, String isactive) {
	  DetachedCriteria dc = DetachedCriteria.forClass(entityClass);
	  
	  if(!StringUtil.isNullOrEmpty(rolename)){
		  dc.add(Restrictions.eq("rolename", rolename.trim()));
	  }
	  
	  if(!StringUtil.isNullOrEmpty(isactive)){
		  dc.add(Restrictions.eq("isactive", isactive.trim()));
	  }
	  
	  return dc;
	}
	
	
}
